<template>
  <div>
    <BasicForm @register="registerForm" @submit="getTableData" style="margin: 10px 0"> </BasicForm>
    <!-- <a-tabs v-model:activeKey="activeKey" type="card" size="small">
      <a-tab-pane key="1" :tab="route.meta.title"> -->
    <BasicTable
      :dataSource="formatData"
      :columns="searchInfo.byunit ? listViewHazardColumnbyUnit : listViewHazardColumnbyHazard"
      @register="registerTable"
      :title="route.meta.title"
      size="small"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 250px)' }"
    >
      <template #toolbar>
        <a-button @click="exportInUserToExcel">导出</a-button>
        <a-radio-group v-model:value="searchInfo.byunit" button-style="solid">
          <a-radio-button :value="true">按单元显示</a-radio-button>
          <a-radio-button :value="false">按危险源类别显示</a-radio-button>
        </a-radio-group>
      </template>

      <template #name="{ column, record }">
        <span v-if="record.type" @click="onUnityViewButtonClick(record)">{{
          '单元--' + record.unitname
        }}</span>
        <span v-else-if="record.level != '3'">{{ record.name }}</span>
        <span v-else-if="record.level == '3'" @click="onViewHazardInfoButtonClick(record)">{{
          record.title
        }}</span>
      </template>

      <template #unitname="{ column, record }">
        <span>{{ record?.level == '3' ? record.unitname : '-' }}</span>
      </template>
      <template #ismajor="{ column, record }">
        <template v-if="record?.level == '3'">
          <Tag v-if="record.ismajor" color="#cd201f">重大</Tag>
          <Tag v-else color="#3b5999">一般</Tag>
        </template>
        <span v-else>-</span>
      </template>

      <template #categoryname="{ column, record }">
        <template v-if="record?.level == '3'">
          <span>{{ record.categoryname }}</span>
        </template>
        <span v-else>-</span>
      </template>

      <template #projectname="{ column, record }">
        <template v-if="record?.level == '3'">
          <span>{{ record.projectname }}</span>
        </template>
        <span v-else>-</span>
      </template>

      <template #identificationresult="{ column, record }">
        <template v-if="record?.level == '3'">
          <Tag
            :color="
              identifyOptions.filter((item) => item.value == record.identificationresult)[0]?.color
            "
          >
            {{
              identifyOptions.filter((item) => item.value == record.identificationresult)[0]?.text
            }}</Tag
          >
        </template>
        <span v-else>-</span>
      </template>
      <template #risklevel="{ column, record }">
        <template v-if="record?.level == '3' && record.risklevel">
          <Tag :color="riskLevelOptions.filter((item) => item.value == record.risklevel)[0]?.color">
            {{ riskLevelOptions.filter((item) => item.value == record.risklevel)[0]?.text }}</Tag
          >
        </template>
        <span v-else>-</span>
      </template>
      <template #action="{ column, record, index }">
        <TableAction
          v-if="mode == 'identify' && record?.level == '3'"
          :actions="[
            {
              label: '辨识',
              onClick: onIdentifyButtonClick.bind(null, record),
            },
          ]"
        />

        <TableAction
          v-if="mode == 'evaluate' && record?.level == '3'"
          :actions="[
            {
              label: '风险评价',
              onClick: onEvaluateButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <!-- </a-tab-pane>
      <a-tab-pane key="2" tab="汇总统计">
        <div style="background-color: #fff; padding: 10px">
          <IdentifyResultStatistic :statisticResult="tableData" />
        </div>
      </a-tab-pane>
    </a-tabs> -->
    <HazardIndentifyModal
      :orgcode="organizationCode"
      @register="registerHazardIdentifyModal"
      @success="opSuccess"
      style="background: #fff"
    />
    <HazardEvaluateModal @register="registerHazardEvaluateModal" @success="opSuccess" />
    <UnitBasicInfoDrawer @register="registerUnitBasicInfo" />
    <HazardInfo @register="registerLogsModal" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, reactive, onMounted, watch, nextTick } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, TableAction, useTable } from '/@/components/Table/index';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { queryHazardLedger } from '/@/api/ehs/hazard';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import {
    listViewConditionFormSchema,
    listViewHazardColumnbyHazard,
    listViewHazardColumnbyUnit,
  } from './hazard.data';
  import IdentifyResultStatistic from './IdentifyResultStatistic.vue';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import { useRoute } from 'vue-router';
  import HazardIndentifyModal from './HazardIndentifyModal.vue';
  import HazardEvaluateModal from './HazardEvaluateModal.vue';
  import { Tag } from 'ant-design-vue';
  import * as XLSX from 'xlsx';
  import UnitBasicInfoDrawer from '../unitDivision/UnitBasicInfoDrawer.vue';
  import HazardInfo from './HazardInfo.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  const { globalProjectCode } = useGlobSetting();
  import { useMessage } from '/@/hooks/web/useMessage';
  export default defineComponent({
    name: 'HazardViewLedger',
    components: {
      BasicTable,
      TableAction,
      HazardIndentifyModal,
      HazardEvaluateModal,
      HazardInfo,
      Tag,
      IdentifyResultStatistic,
      UnitBasicInfoDrawer,
      BasicForm,
    },
    setup(_, { emit }) {
      const route = useRoute();
      const { createMessage } = useMessage();
      const organizationCode = ref();
      const projectCode = ref<String>(globalProjectCode);
      const mode = ref('ledger');
      const identifyOptions = ref();
      const riskLevelOptions = ref('');
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const state = reactive({
        searchText: '',
        searchedColumn: '',
      });
      const activeKey = ref('1');
      const tableData = ref({
        items: [],
      });
      // 经过格式处理后的数据
      const formatData = ref([]);
      const searchInfo = reactive({
        isdept: false,
        byunit: true,
      });
      const [registerHazardIdentifyModal, { openModal: openHazardIndentify }] = useModal();
      const [registerHazardEvaluateModal, { openModal: openHazardEvaluate }] = useModal();
      const [registerLogsModal, { openDrawer: openLogsDrawer }] = useDrawer();
      const [registerUnitBasicInfo, { openDrawer: openUnitBasicInfoDrawer }] = useDrawer();
      const [registerForm, { setFieldsValue, getFieldsValue, updateSchema }] = useForm({
        schemas: listViewConditionFormSchema,
        showResetButton: false,
        actionColOptions: { span: 2 },
      });
      const searchInput = ref();
      const [registerTable, { setColumns, reload, getDataSource, setLoading, expandAll }] =
        useTable({
          canResize: true,
          showTableSetting: true,
          tableSetting: {
            redo: false,
          },
          striped: false,
          showIndexColumn: false,
          isTreeTable: true,
          bordered: true,
          ellipsis: true,
          indentSize: 30,
          actionColumn: {
            width: 120,
            ifShow:
              route.query.mode == 'identify' ||
              route.query.mode == 'evaluate' ||
              route.fullPath.split('/').at(-1) == 'identify' ||
              route.fullPath.split('/').at(-1) == 'evaluate',
            title: '操作',
            dataIndex: 'action',
            slots: { customRender: 'action' },
            fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
          },
        });
      function opSuccess() {
        getTableData();
      }

      // 合并相同单元的excel单元格
      function computeMergeRow(data) {
        //计算合并行，数据中每条数据已有合并行rowSpan
        let groupData = JSON.parse(JSON.stringify(data));
        let mergesArr = [];
        //内容数据合并单元格 根据单元和根据类别的处理方式不一样
        if (searchInfo.byunit) {
          let start = 2;
          let end = 2;
          //内容数据合并单元格
          for (let i = 1; i < groupData.length; i++) {
            let preHazard;
            let curHazard;
            preHazard = groupData[i - 1].unitid;
            curHazard = groupData[i].unitid;
            if (preHazard !== curHazard) {
              if (start !== end) mergesArr.push('A' + start + ':' + 'A' + end);
              start = i + 2;
              end = i + 2;
            } else {
              end++;
              if (i === groupData.length - 1) mergesArr.push('A' + start + ':' + 'A' + end);
            }
          }
        } else {
          let categoryStart = 2;
          let projectStart = 2;
          groupData.forEach((category, index) => {
            mergesArr.push(`A${categoryStart}:A${categoryStart + category.itemCol - 1}`);
            categoryStart = categoryStart + category.itemCol;
            if (category.children)
              category.children.forEach((project) => {
                mergesArr.push(`B${projectStart}:B${projectStart + project.itemCol - 1}`);
                projectStart = projectStart + project.itemCol;
              });
          });
        }
        // console.log('需要合并的单元格', mergesArr);
        return mergesArr;
      }

      //需要导出的数组数据
      let ledgerData = [];

      /**
       * 导出功能
       */
      function exportInUserToExcel() {
        const filename = `危险源台账.xlsx`; //导出文件名
        const worksheet_name = 'Sheet1'; // Excel第一个sheet的名称
        const workbook = XLSX.utils.book_new(); //创建一个新的workbook
        const worksheet = XLSX.utils.aoa_to_sheet(ledgerData);
        console.log(ledgerData, 'ledgerData');
        //合并单元格
        //找出需要合并的单元格位置数组
        // let mergesArr;
        // if (searchInfo.byunit) {
        //   mergesArr = computeMergeRow(
        //     treeToArray(formatData.value).filter((item) => item.hazardid),
        //   );
        // } else {
        //   mergesArr = computeMergeRow(
        //     JSON.parse(JSON.stringify(formatData.value.map(mergeCategoryAndProjectArr))),
        //   ); //['A1:A2','B1:B2',...]
        // }
        // console.log('mergesArr', mergesArr);
        // let arr = [];
        // mergesArr.forEach((merge) => {
        //   arr.push(XLSX.utils.decode_range(merge));
        // });
        worksheet['!merges'] = [];

        //列宽设置
        worksheet['!cols'] = [
          { width: 40 },
          { width: 30 },
          { width: 40 },
          { width: 40 },
          { width: 40 },
          { width: 40 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
        ];

        //保存数据信息并下载文件
        XLSX.utils.book_append_sheet(workbook, worksheet, worksheet_name); //将数据添加到工作簿
        XLSX.writeFile(workbook, filename); //下载excel文件
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];
        //递归函数 traverse，用于处理单个节点
        function traverse(node) {
          const newNode = { ...node };
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach(traverse);
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      // 计算类别和项目单元格的itemCol
      // function mergeCategoryAndProjectArr(data) {
      //   let count = 0;
      //   if (data.children) {
      //     data.children = data.children.map((item) => {
      //       if (item.children) count += item.children.length;
      //       return { ...item, itemCol: item.children.length };
      //     });
      //   }
      //   return {
      //     itemCol: count,
      //     ...data,
      //   };
      // }

      // 获取表格数据
      function getTableData() {
        setLoading(true);
        let formValue = getFieldsValue();
        let tmp = {
          includechilds: true,
          ...formValue,
          ...searchInfo,
          orgcode: organizationCode.value,
          isconstruction: !formValue.isconstruction ? null : true,
        };
        queryHazardLedger(tmp)
          .then((res) => {
            tableData.value = res;
            formatData.value = res.items
              ? JSON.parse(JSON.stringify(ledgerDataFormat(res.items)))
              : [];
            if (res.items == null) {
              setLoading(false);
              return createMessage.error('暂无危险源!');
            }
            let tmp = [];
            if (res.items) {
              res.items.hazards.forEach((hazard) => {
                let value = {};
                value = {
                  title: hazard.title,
                  unitname: hazard.unitname,
                  categoryname: hazard.categoryname,
                  projectname: hazard.projectname,
                  hazardname: hazard.hazardname,
                  couse: hazard.couse,
                  ismajor: hazard.ismajor === true ? '重大' : '一般',
                  identificationresult: identifyOptions.value.filter(
                    (item) => item.value == hazard.identificationresult,
                  )[0]?.text,
                  risklevel: riskLevelOptions.value.filter(
                    (item) => item.value == hazard.risklevel,
                  )[0]?.text,
                };
                tmp.push(value);
              });
            }

            tmp.unshift([
              '标题',
              '单元',
              '所属类别',
              '所属项目',
              '危险源名称',
              '诱因',
              '是否重大',
              '辨识结果',
              '风险等级',
            ]);
            ledgerData = tmp.map((item) => {
              return Object.keys(item).map((key) => item[key]);
            });
            setLoading(false);
            nextTick(expandAll);
          })
          .catch((err) => {
            console.log(err, 'e');
            setLoading(false);
          });
      }

      /**
       *
       * 单元基础信息弹窗查看
       */
      function onUnityViewButtonClick(record) {
        if (record.type && record.type == 1) {
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '单元基础信息',
            operateType: OperationTypeEnum.VIEW,
            dataId: record.unitid,
          };
          openUnitBasicInfoDrawer(true, propsData);
        }
      }

      /**
       * 辨识
       */
      function onIdentifyButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源辨识/上报隐患',
          operateString: '填报',
          dataId: record.hazardid,
          index: null,
        };
        openHazardIndentify(true, propsData);
      }

      /**
       * 评价
       */
      function onEvaluateButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源风险评价',
          operateString: record.hazardname,
          dataId: record.hazardid,
        };
        openHazardEvaluate(true, propsData);
      }

      /**
       * 查看危险源信息
       */
      function onViewHazardInfoButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源信息',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.hazardid,
        };
        openLogsDrawer(true, propsData);
      }

      /**
       * 台账数据格式处理
       */
      function ledgerDataFormat(data) {
        let result = [];
        let units = data.units;
        let hazards = data.hazards;
        let categorys = data.categorys;
        if (searchInfo.byunit) {
          function setUnitsHazard(unitItem) {
            let unit = {
              ...unitItem.info,
              type: 1,
              children: [],
            };
            if (unitItem.children?.length > 0) {
              unit.children = unitItem.children.map(setUnitsHazard);
            }
            unit.children = [
              ...unit.children,
              ...hazards
                .filter((item) => item.unitid == unitItem.info.unitid)
                .map((item) => {
                  return { ...item, level: '3' };
                }),
            ];
            if (unit.children?.length < 1) delete unit.children;
            return unit;
          }
          result = units.map(setUnitsHazard);
        } else {
          function setCategoryHazard(listItem) {
            let list = {
              code: listItem.code,
              name: listItem.name,
              level: listItem.level,
              children: [],
            };
            if (listItem.children?.length > 0) {
              list.children = listItem.children.map(setCategoryHazard);
            }
            if (listItem.level == '3') {
              list = {
                ...list,
                ...hazards.find((item) => item.hazardid == listItem.code),
              };
            }
            if (list.children.length < 1) delete list.children;
            return list;
          }
          result = categorys.map(setCategoryHazard);
        }
        return result;
      }

      watch(
        () => searchInfo.byunit,
        (byunit: boolean) => {
          getTableData();
          let column = listViewHazardColumnbyUnit.find(
            (item) => item.dataIndex == 'identificationresult',
          );
          let column2 = listViewHazardColumnbyHazard.find(
            (item) => item.dataIndex == 'identificationresult',
          );
          column.ifShow = !(
            mode.value == 'dangerledger' ||
            mode.value == 'majordanger' ||
            mode.value == 'majorrisks' ||
            mode.value == 'risksledger'
          );
          column2.ifShow = !(
            mode.value == 'dangerledger' ||
            mode.value == 'majordanger' ||
            mode.value == 'majorrisks' ||
            mode.value == 'risksledger'
          );
          setColumns(byunit ? column : column2);
          reload();
        },
      );

      onMounted(() => {
        getUserOrganization(projectCode.value).then((res) => {
          // 请求时需要传入用户的组织编码
          organizationCode.value = res?.orgcode;
          queryUnitDivision({
            includechilds: true,
            isdept: false,
            flagisvalid: false,
            orgcode: res.orgcode,
          })
            .then((res) => {
              //父级单元选项集合
              queryEnumOptions('EhsRiskLevelEnum,EhsHazardIndentificationResultTypeEnum').then(
                (res2) => {
                  if (res2 != undefined && res2 != null && res2.length > 0x0) {
                    const riskOp = res2[0].options.map((option) => {
                      return {
                        value: option.key,
                        text: option.value,
                        color: option.attribute.split('"')[3],
                      };
                    });
                    const identifyOp = res2[1].options.map((option) => {
                      return {
                        value: option.key,
                        text: option.value,
                        color: option.attribute.split('"')[3],
                      };
                    });
                    identifyOptions.value = identifyOp;
                    riskLevelOptions.value = riskOp;
                    updateSchema([
                      {
                        field: 'unitid',
                        componentProps: {
                          allowClear: true,
                          treeData: res,
                          fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                          treeDefaultExpandAll: true, //默认展开
                          listHeight: 250, //设置弹窗滚动高度
                        },
                      },
                      {
                        field: 'risklevel',
                        componentProps: {
                          allowClear: true,
                          options: res2[0].options.map((op) => {
                            return {
                              label: op.value,
                              value: op.key,
                            };
                          }),
                        },
                      },
                    ]);
                    getTableData();
                  }
                },
              );
            })
            .catch((ex) => {
              console.log('catch ', ex);
            });
        });
        setLoading(true);
        mode.value = route.query.mode ?? route.fullPath.split('/').at(-1);
        console.log(mode.value, 'mode');
        updateSchema([
          {
            field: 'ishidden',
            show: !(
              mode.value == 'dangerledger' ||
              mode.value == 'majordanger' ||
              mode.value == 'majorrisks' ||
              mode.value == 'risksledger'
            ),
          },
          {
            field: 'ismajor',
            show: !(mode.value == 'majordanger' || mode.value == 'majorrisks'),
          },
        ]);
        let column = listViewHazardColumnbyUnit.find(
          (item) => item.dataIndex == 'identificationresult',
        );
        column.ifShow = !(
          mode.value == 'dangerledger' ||
          mode.value == 'majordanger' ||
          mode.value == 'majorrisks' ||
          mode.value == 'risksledger'
        );
        setColumns(column);
        // 获取路由携带数据
        setFieldsValue({
          ...route.query,
          ismajor:
            mode.value == 'majordanger' || mode.value == 'majorrisks'
              ? '1'
              : route.query.ismajor ?? null,
          risklevel: route.query.risklevel ? route.query.risklevel : null,
          unitid: route.query.unitid,
          ishidden:
            mode.value == 'evaluate' || mode.value == 'dangerledger' || mode.value == 'majordanger'
              ? '0'
              : mode.value == 'majorrisks' || mode.value == 'risksledger'
              ? '1'
              : route.query.ishidden ?? null,
        });
      });
      return {
        state,
        mode,
        organizationCode,
        activeKey,
        route,
        tableData,
        formatData,
        searchInput,
        riskLevelOptions,
        identifyOptions,
        searchInfo,
        registerHazardIdentifyModal,
        registerHazardEvaluateModal,
        registerUnitBasicInfo,
        registerLogsModal,
        registerTable,
        opSuccess,
        registerForm,
        getTableData,
        onUnityViewButtonClick,
        exportInUserToExcel,
        onIdentifyButtonClick,
        onEvaluateButtonClick,
        onViewHazardInfoButtonClick,
        listViewHazardColumnbyUnit,
        listViewHazardColumnbyHazard,
      };
    },
  });
</script>

<style scoped>
  .ant-col-14 {
    flex: 1;
  }
  .vben-basic-form .ant-form-item {
    margin-bottom: 0px;
  }
  label.ant-radio-button-wrapper {
    min-width: 90px;
    text-align: center;
  }
  .ismajorButton .ant-radio-button-wrapper:nth-child(2).ant-radio-button-wrapper-checked {
    background-color: rgb(59, 89, 153);
    color: #fff;
    border: 1px solid rgb(59, 89, 153);
  }
  .ismajorButton .ant-radio-button-wrapper:nth-child(3).ant-radio-button-wrapper-checked {
    background-color: rgb(205, 32, 31);
    color: #fff;
    border: 1px solid rgb(205, 32, 31);
  }
  .ismajorButton .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled)::before {
    background: rgb(203, 203, 203);
  }
</style>
